package com.yq.emp.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecuConfig extends WebSecurityConfigurerAdapter {
    //静态资源不拦截
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/css/**")
        .antMatchers("/fonts/**")
        .antMatchers("/images/**")
        .antMatchers("/js/**");
    }

    //配置资源访问控制
    // csrf().disable() 阻止csrf攻击
    //authorizeRequests() 认证请求
    //permitAll() 不需要认证
    //authenticated() 认证用户访问
    //antMatchers 认证路径
    @Override
    protected void configure(HttpSecurity http) throws Exception {
       http.csrf().disable().authorizeRequests().antMatchers("/").permitAll()
               .antMatchers("/**").authenticated();
       //开启表单验证用户   loginPage登录页面处理器   /login security提供用户认证处理器  failureForwardUrl认证失败转到rul  认证成功 url  defaultSuccessUrl
        http.formLogin().loginPage("/").loginProcessingUrl("/login").failureForwardUrl("/").defaultSuccessUrl("/main");
        //开启退出功能    退出系统转向页面
        http.logout().logoutSuccessUrl("/");

        //开启集中账户功能
        http.rememberMe().rememberMeParameter("rememberMe");
    }
    //认证方法
    //inMemoryAuthentication() 内存认证
    //passwordEncoder() 设置密码编码格式
    //roles 用户角色
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("admin").password(new BCryptPasswordEncoder().encode("123")).roles("admin").and()
                .withUser("staff").password(new BCryptPasswordEncoder().encode("123")).roles("staff");
    }
}
